import logging
from typing import Any

from aiogram import types
from aiogram_dialog import DialogManager
from fluentogram import TranslatorRunner

from src.presentation.tg_bot.states import SelectProxySG


async def set_proxy_type(_, widget: Any, manager: DialogManager):
    manager.dialog_data["proxy_type"] = widget.widget_id
    await manager.next()


async def set_site_id(_, __, manager: DialogManager, site_id: str):
    manager.dialog_data["site_id"] = int(site_id)
    await manager.next()


async def set_proxy_privacy(_, widget: Any, manager: DialogManager):
    manager.dialog_data["proxy_privacy"] = widget.widget_id
    await manager.next()


async def set_proxy_provider(_, __, manager: DialogManager, provider_id: str):
    manager.dialog_data["provider_id"] = provider_id

    if manager.start_data and manager.start_data.get("for_test"):
        manager.dialog_data["period"] = "twenty_minutes"
        await manager.switch_to(SelectProxySG.set_order_quantity)
    elif manager.dialog_data.get("proxy_privacy") == "private":
        await manager.switch_to(SelectProxySG.select_period)
    else:
        await manager.switch_to(SelectProxySG.select_category)


async def set_proxy_period(_, widget: Any, manager: DialogManager):
    manager.dialog_data["period"] = widget.widget_id
    await manager.next()


async def back_to_provider(_, __, manager: DialogManager):
    await manager.switch_to(SelectProxySG.select_provider)


async def set_order_quantity(message: types.Message, _, manager: DialogManager, selected_amount: str):
    locale: TranslatorRunner = manager.middleware_data.get("locale")

    selected_amount = int(selected_amount)

    if selected_amount <= 0:
        await message.answer(locale.get("number-must-be-positive"))
        return

    manager.dialog_data["user_id"] = message.from_user.id

    if selected_amount > manager.dialog_data.get("available_amount"):
        await message.answer(locale.get("too-much-quantity"))
        return

    manager.dialog_data["selected_amount"] = selected_amount

    await manager.next()
